# 使用 scrcpy 将手机屏幕内容投屏到电脑。
# 使用 OpenCV 捕获 scrcpy 窗口的内容。
# 将捕获的内容逐帧发送到虚拟摄像头。

import cv2
import numpy as np
import pyautogui
import pyvirtualcam
import pygetwindow as gw


# 获取 scrcpy 窗口
def find_scrcpy_window():
    windows = gw.getWindowsWithTitle("2312DRAABC")
    print(windows)
    if len(windows) == 0:
        raise Exception("未找到 scrcpy 窗口，请确保 scrcpy 已启动并连接手机。")
    return windows[0]


# 主程序
def main():
    # 找到 scrcpy 窗口
    scrcpy_window = find_scrcpy_window()
    print(f"找到 scrcpy 窗口: {scrcpy_window.title}")

    # 获取窗口位置和大小
    x, y, width, height = scrcpy_window.left, scrcpy_window.top, scrcpy_window.width, scrcpy_window.height

    # 设置虚拟摄像头
    with pyvirtualcam.Camera(width=width, height=height, fps=30) as cam:
        print(f"正在使用虚拟摄像头: {cam.device}")
        while True:
            # 捕获 scrcpy 窗口内容
            screenshot = pyautogui.screenshot(region=(x, y, width, height))

            # 将截图转换为 NumPy 数组
            frame = np.array(screenshot)

            # 将图像从 RGB 转换为 BGR（OpenCV 格式）
            frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

            # 将帧发送到虚拟摄像头
            cam.send(frame)

            # 等待下一帧
            cam.sleep_until_next_frame()


if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"程序运行时出现错误: {e}")
    # for win in gw.getAllTitles():
    #     print(win)
